package com.syblood.app.ui.activities;

import android.app.Activity;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.syblood.app.R;
import com.syblood.app.application.AppContext;
import com.syblood.app.camera.DoubleCameraGLSurfaceView;
import com.syblood.app.camera.callback.ICameraGLSurfaceViewCallback;
import com.syblood.app.constants.Constants;
import com.syblood.app.handler.CameraOneHandler;
import com.syblood.app.ui.activities.base.BaseActivity;
import com.syblood.app.utils.ConstantsUtils;
import com.syblood.app.utils.DoubleClickExitHelper;
import com.syblood.app.utils.PermisionUtil;
import com.syblood.app.utils.ToastUtil;


public class DoubleCameraActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = ConstantsUtils.TAG_HEAD + String.class.getSimpleName();
    public static Activity instance;

    private FrameLayout mDoubleCameraFl;
    private DoubleCameraGLSurfaceView mCameraGLSurfaceView;
    private TextView mAspectRatioTv;
    private CameraOneHandler mCameraOneHandler;
    private CameraOneHandler mCameraOneHandler2;

    DoubleClickExitHelper mDoubleClickExit;
    private String mCameraId0;
    private String mCameraId1;

    private CameraManager mCameraManager;
    private int curAspectRatio = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_double_camera;
    }

    @Override
    public void initActionBar() {
        super.initActionBar();
    }

    @Override
    public void initData() {
        super.initData();
        PermisionUtil.verifyStoragePermissions(this);
        instance = this;
        mDoubleClickExit = new DoubleClickExitHelper(this);
    }

    @Override
    public void initWidget() {
        super.initWidget();
        mCameraGLSurfaceView = findViewById(R.id.glsf_doublecamera);
        mDoubleCameraFl = findViewById(R.id.fl_doublecamera);
        mAspectRatioTv = findViewById(R.id.tv_aspect_ratio);
        findViewById(R.id.tv_camera1).setOnClickListener(this);
        findViewById(R.id.tv_camera2).setOnClickListener(this);
        findViewById(R.id.tv_record).setOnClickListener(this);
        findViewById(R.id.tv_aspect_ratio).setOnClickListener(this);


        loadCameraId();
    }

    /**
     * 监听返回时间，二次点击退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 是否退出应用
            if (AppContext.get(Constants.KEY_DOUBLE_CLICK_EXIT, true)) {
                return mDoubleClickExit.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();


        mCameraGLSurfaceView.setCallback(new ICameraGLSurfaceViewCallback() {
            @Override
            public void onSurfaceViewCreate(SurfaceTexture texture, int width, int height) {
                if (mCameraOneHandler == null) {
                    mCameraOneHandler = new CameraOneHandler((BaseActivity) aty, mCameraGLSurfaceView.getCamera1SurfaceTexture(), mCameraManager, mCameraId0);
                }
                if (mCameraOneHandler2 == null) {
                    mCameraOneHandler2 = new CameraOneHandler((BaseActivity) aty, mCameraGLSurfaceView.getCamera2SurfaceTexture(), mCameraManager, mCameraId1);
                }
                Log.d(TAG, "onSurfaceViewCreate mCameraTexture1 = " + mCameraGLSurfaceView.getCamera1SurfaceTexture() + " , mCameraTexture2 = " + mCameraGLSurfaceView.getCamera2SurfaceTexture());
                mCameraOneHandler.getCameraGLSurfaceViewCallback().onSurfaceViewCreate(mCameraGLSurfaceView.getCamera1SurfaceTexture(), width, height);
                mCameraOneHandler2.getCameraGLSurfaceViewCallback().onSurfaceViewCreate(mCameraGLSurfaceView.getCamera2SurfaceTexture(), width, height);
            }

            @Override
            public void onSurfaceViewChange(int width, int height) {
                if (mCameraOneHandler == null) {
                    mCameraOneHandler = new CameraOneHandler((BaseActivity) aty, mCameraGLSurfaceView.getCamera1SurfaceTexture(), mCameraManager, mCameraId0);
                }
                if (mCameraOneHandler2 == null) {
                    mCameraOneHandler2 = new CameraOneHandler((BaseActivity) aty, mCameraGLSurfaceView.getCamera2SurfaceTexture(), mCameraManager, mCameraId1);
                }
                mCameraOneHandler.getCameraGLSurfaceViewCallback().onSurfaceViewChange(width, height);
                mCameraOneHandler2.getCameraGLSurfaceViewCallback().onSurfaceViewChange(width, height);
            }
        });

        mCameraGLSurfaceView.setAspectRatio(1200, 1600);

//        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mDoubleCameraFl.getLayoutParams();
//        lp.height = lp.width * 3 / 4;
//
//        mDoubleCameraFl.setLayoutParams(lp);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
    }


    public void loadCameraId() {
        mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
        try {
            String[] ids = mCameraManager.getCameraIdList();
            //获取可用摄像头列表
            for (String cameraId : ids) {
                //获取相机的相关参数
                CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
                // 不使用前置摄像头。
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
                    mCameraId0 = cameraId;
                } else {
                    mCameraId1 = cameraId;
                }
            }
        } catch (CameraAccessException e) {
            Log.w("初始化摄像头失败", e);
        } catch (NullPointerException e) {
            Log.w("初始化摄像头失败", e);
            //不支持Camera2API

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_camera1:
                if (mCameraOneHandler != null && !mCameraOneHandler.isPreview()) {
                    mCameraOneHandler.initView();
                }
                break;
            case R.id.tv_camera2:
                if (mCameraOneHandler2 != null && !mCameraOneHandler2.isPreview()) {
                    mCameraOneHandler2.initView();
                }
                break;
            case R.id.tv_record:
                if (mCameraGLSurfaceView.isRecording()) {
                    mCameraGLSurfaceView.stopRecord();
                    ToastUtil.show(aty, "停止录制");
                } else {
                    mCameraGLSurfaceView.startRecord();
                    ToastUtil.show(aty, "开始录制");
                }
                break;
            case R.id.tv_aspect_ratio:
                curAspectRatio = (curAspectRatio + 1) % 3;
                if (curAspectRatio == 0) {
                    mCameraGLSurfaceView.setAspectRatio(1200, 1600);
                    mAspectRatioTv.setText("纵横比：4:3");

                } else if (curAspectRatio == 1) {
                    mCameraGLSurfaceView.setAspectRatio(900, 1600);
                    mAspectRatioTv.setText("纵横比：16:9");
                } else if (curAspectRatio == 2) {
                    mCameraGLSurfaceView.setAspectRatio(1600, 1600);
                    mAspectRatioTv.setText("纵横比：1:1");
                }
                mCameraOneHandler.stopHandlerThread();
                mCameraOneHandler2.stopHandlerThread();

                mCameraOneHandler.initView();
                mCameraOneHandler2.initView();
                break;
        }
    }
}